package net.hserver.apm.service;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Sorts;
import net.hserver.apm.config.MongodbConfig;
import org.bson.Document;
import org.bson.conversions.Bson;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.ioc.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

@Bean
public class SqlInfoService {

    @Autowired
    private MongoClient mongoClient;

    public List<Document> getSqlInfo(String chainId) {
        MongoDatabase database = mongoClient.getDatabase(MongodbConfig.DATA_BASE);
        MongoCollection<Document> sqlInfo = database.getCollection("sqlInfo");
        Bson bson = null;
        if (chainId != null && chainId.trim().length() > 0) {
            bson = Filters.and(Filters.eq("chainId", chainId));
        }
        MongoCursor<Document> time;
        if (bson == null) {
            time = sqlInfo.find().sort(Sorts.descending( "time")).iterator();
        } else {
            time = sqlInfo.find(bson).sort(Sorts.descending( "time")).iterator();
        }
        List<Document> data = new ArrayList<>();
        try {
            while (time.hasNext()) {
                data.add(time.next());
            }
        } finally {
            time.close();
        }
        return data;
    }

}
